package mspbots.cw.business.core.contacts;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.business.core.BaseReceiver;
import mspbots.cw.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.Iterator;

/**
 * @author Jay.Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ContactsReceiver extends BaseReceiver {

    private final ContactsRepository contactsRepository;

    @RabbitListener(queues = "connect-wise.contacts.tl")
    public void process(ResultMsg resultMsg) {
        JsonNode entity = resultMsg.getEntity();
        Contacts data = super.objectMapper.convertValue(entity, Contacts.class);
        data.setId(null);
        data.setContactsId(resultMsg.getId());
        data.setTenantCode(resultMsg.getTenantId());
        data.setSyncTime(resultMsg.getSyncDate());

        data.setSiteId(super.getLongValueId(entity.get("site")));
        data.setSiteName(super.getStringValueName(entity.get("site")));
        data.setCompanyId(super.getLongValueId(entity.get("company")));
        data.setCompanyName(super.getStringValueName(entity.get("company")));
        data.setCompanyLocationId(super.getLongValueId(entity.get("companyLocation")));
        data.setCompanyLocationName(super.getStringValueName(entity.get("companyLocation")));

        if (!ObjectUtils.isEmpty(entity.get("communicationItems"))) {
            Iterator<JsonNode> nodeJson = entity.get("communicationItems").elements();
            while (nodeJson.hasNext()) {
                JsonNode item = nodeJson.next();
                if (!ObjectUtils.isEmpty(item.get("communicationType"))
                        && "email".equalsIgnoreCase(super.getStringValue(item.get("communicationType")))) {
                    data.setEmail(super.getStringValue(item.get("value")));
                    break;
                }
            }
        }

        this.contactsRepository.findByContactsIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.contactsRepository::save).block(Duration.ofSeconds(10));
    }

}
